package net.chengp.esload4j.source.mysql.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.shyiko.mysql.binlog.event.TableMapEventData;

import net.chengp.esload4j.config.ESLoad4jConfig.MysqlSourceConfig;
import net.chengp.esload4j.db.jdbc.BaseDao;
import net.chengp.esload4j.db.jdbc.BaseDaoImpl;

/**
 * 
 * @author chengp
 * @email E-mail:chengp@chengp.net
 * @version 创建时间：2020年9月12日 下午3:22:55 
 *
 */
public class MySQLDaoImpl extends BaseDaoImpl implements BaseDao {

	private static final Map<Long, List<Map<String, Object>>> tableColumnsCache = new HashMap<Long, List<Map<String, Object>>>();

	public MySQLDaoImpl(String id, String driver, String host, String port, String username, String password) {
		super(id, driver, host, port, username, password);
	}

	public MySQLDaoImpl(MysqlSourceConfig mysqlSourceConfig) {
		super(mysqlSourceConfig.getId(), mysqlSourceConfig.getDriver(), mysqlSourceConfig.getHost(),
				String.valueOf(mysqlSourceConfig.getPort()), mysqlSourceConfig.getUsername(),
				mysqlSourceConfig.getPassword());
	}

	public List<Map<String, Object>> getTableColumns(TableMapEventData tmed) throws Exception {
		List<Map<String, Object>> tableColumns = tableColumnsCache.get(tmed.getTableId());
		if (tableColumns == null || tableColumns.size() <= 0) {
			tableColumns = this.queryAllForMap(
					"select * from information_schema.columns where table_schema=? and table_name=? order by ordinal_position",
					new Object[] { tmed.getDatabase(), tmed.getTable() });
			tableColumnsCache.put(tmed.getTableId(), tableColumns);
		}
		return tableColumns;
	}

	public List<Map<String, Object>> getTableDatas(String tableName) throws Exception {
		return this.queryAllForMap("select * from " + tableName, null);
	}

	public List<Map<String, Object>> getTableDatasPage(String tableName, long start, long size) throws Exception {
		return this.queryAllForMap("select * from " + tableName + " limit " + start + "," + size, null);
	}

	public long count(String tableName) throws Exception {
		return super.count(tableName);
	}

}
